package com.magist.core.entity;

import com.magist.core.auth.AuthUser;

import java.util.HashMap;
import java.util.Map;

public class CxtHolder {
	private final static String REQUEST = "request";
	private final static String SESSION = "session";

	static private ThreadLocal<Map<String, Object>> tl = new ThreadLocal<Map<String, Object>>();

	private static Map<String, Object> getMap() {
		Map<String, Object> map = tl.get();
		if (map == null) {
			map = new HashMap<String, Object>();
			tl.set(map);
			return map;
		} else {
			return map;
		}

	}

	/**
	 * 获取值
	 * 
	 * @param key
	 * @return
	 */
	public static Object get(String key) {
		return getMap().get(key);
	}

	/**
	 * 设置对象
	 * 
	 * @param key
	 * @param obj
	 * @return
	 */
	public static Object put(String key, Object obj) {
		return getMap().put(key, obj);
	}

	/**
	 * 清求对象设置
	 * 
	 * @param request
	 */
	public static void setRequest(CxtRequest request) {
		put(REQUEST, request);
	}

	/**
	 * 获取请求对象
	 * 
	 * @return
	 */
	public static CxtRequest getRequest() {
		Object o = get(REQUEST);
		if (o != null)
			return (CxtRequest) o;
		return null;
	}

	/**
	 * 会话对象设置
	 * 
	 * @param session
	 */
	public static void setSession(CxtSession session) {
		put(SESSION, session);
	}

	/**
	 * 得到会话对象
	 * 
	 * @return
	 */
	public static CxtSession getSession() {
		Object o = get(SESSION);
		if (o != null)
			return (CxtSession) o;
		return null;
	}

	/**
	 * 当前用户设置
	 * 
	 * @param session
	 */
	public static void setUser(AuthUser user) {
		CxtRequest request = getRequest();
		if (request != null)
			request.setUser(user);
	}

	/**
	 * 得到当前用户
	 * 
	 * @return
	 */
	public static AuthUser getUser() {
		CxtRequest request = getRequest();
		if (request != null)
			return request.getUser();
		return null;
	}
}
